<template>
  <view class="file-upload-page">
    <!-- 导航栏 -->
    <u-navbar 
      title="文件上传" 
      :border="false"
      left-icon="arrow-left"
      @leftClick="goBack"
      :background="{ background: 'linear-gradient(135deg, #4a6bef, #7a5af8)' }"
      :titleStyle="{ color: '#ffffff', fontSize: '34rpx', fontWeight: 'bold' }"
      :leftIconColor="'#ffffff'"
    />
    
    <!-- 上传区域 -->
    <view class="upload-section">
      <view class="upload-tips">
        <u-icon name="info-circle" color="#4a6bef" size="18"></u-icon>
        <text class="tips-text">支持PDF、Word、Excel、PPT、图片等格式，单个文件不超过50MB</text>
      </view>
      
      <!-- 文件选择器 -->
      <view class="upload-area" @tap="chooseFile">
        <view v-if="!selectedFile" class="upload-placeholder">
          <u-icon name="plus" size="48" color="#c0c4cc"></u-icon>
          <text class="placeholder-text">点击选择文件</text>
          <text class="placeholder-desc">或拖拽文件到此处</text>
        </view>
        
        <view v-else class="selected-file">
          <view class="file-info">
            <view class="file-icon">
              <u-icon :name="getFileIcon(selectedFile.type)" size="28" color="#4a6bef"></u-icon>
            </view>
            <view class="file-details">
              <text class="file-name">{{ selectedFile.name }}</text>
              <text class="file-size">{{ formatFileSize(selectedFile.size) }}</text>
            </view>
          </view>
          <view class="file-remove" @tap.stop="removeFile">
            <u-icon name="close-circle-fill" size="24" color="#f56c6c"></u-icon>
          </view>
        </view>
      </view>
      
      <!-- 上传进度 -->
      <view v-if="uploading" class="upload-progress">
        <u-line-progress 
          :percent="uploadProgress" 
          :show-percent="true"
          activeColor="#4a6bef"
          height="16"
        />
        <text class="progress-text">正在上传...{{ uploadProgress }}%</text>
      </view>
      
      <!-- 上传按钮 -->
      <button 
        class="upload-btn"
        :class="{ 'disabled': !selectedFile || uploading }"
        :disabled="!selectedFile || uploading"
        @click="uploadFile"
      >
        <u-icon v-if="uploading" name="reload" size="20" color="#ffffff" class="loading-icon"></u-icon>
        <text>{{ uploading ? '上传中...' : '开始上传' }}</text>
      </button>
    </view>
    
    <!-- 最近上传的文件 -->
    <view class="recent-files" v-if="recentFiles.length > 0">
      <view class="section-title">
        <view class="title-bar"></view>
        <text>最近上传</text>
        <text class="view-all" @tap="viewAllFiles">查看全部</text>
      </view>
      
      <view class="file-list">
        <view 
          v-for="file in recentFiles" 
          :key="file.id"
          class="file-item"
          @tap="viewFile(file)"
        >
          <view class="file-icon">
            <u-icon :name="getFileIcon(file.fileType)" size="24" color="#4a6bef"></u-icon>
          </view>
          <view class="file-info">
            <text class="file-name">{{ file.originalName }}</text>
            <text class="file-meta">{{ formatFileSize(file.fileSize) }} · {{ formatTime(file.createdAt) }}</text>
          </view>
          <u-icon name="arrow-right" size="16" color="#c0c4cc"></u-icon>
        </view>
      </view>
    </view>
    
    <!-- 支持的文件类型说明 -->
    <view class="supported-types">
      <view class="section-title">
        <view class="title-bar"></view>
        <text>支持的文件类型</text>
      </view>
      <view class="type-list">
        <view class="type-category">
          <view class="category-header">
            <u-icon name="file-text" size="20" color="#4a6bef"></u-icon>
            <text class="category-title">文档类型</text>
          </view>
          <view class="type-items">
            <view class="type-tag">PDF</view>
            <view class="type-tag">Word</view>
            <view class="type-tag">Excel</view>
            <view class="type-tag">PPT</view>
            <view class="type-tag">TXT</view>
          </view>
        </view>
        <view class="type-category">
          <view class="category-header">
            <u-icon name="photo" size="20" color="#4a6bef"></u-icon>
            <text class="category-title">图片类型</text>
          </view>
          <view class="type-items">
            <view class="type-tag">JPG</view>
            <view class="type-tag">PNG</view>
            <view class="type-tag">GIF</view>
            <view class="type-tag">BMP</view>
            <view class="type-tag">WebP</view>
          </view>
        </view>
      </view>
      
      <view class="upload-notes">
        <view class="note-item">
          <u-icon name="checkmark-circle" size="16" color="#19be6b"></u-icon>
          <text>文件上传后可以直接打印或分享给他人</text>
        </view>
        <view class="note-item">
          <u-icon name="checkmark-circle" size="16" color="#19be6b"></u-icon>
          <text>支持多种纸张和打印选项</text>
        </view>
        <view class="note-item">
          <u-icon name="checkmark-circle" size="16" color="#19be6b"></u-icon>
          <text>文件将安全存储在云端，随时可访问</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { mapState } from 'vuex'

export default {
  name: 'FileUpload',
  data() {
    return {
      selectedFile: null,
      uploading: false,
      uploadProgress: 0,
      recentFiles: []
    }
  },
  
  computed: {
    ...mapState('user', ['userInfo'])
  },
  
  onLoad() {
    this.loadRecentFiles()
  },
  
  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack()
    },
    
    // 选择文件
    chooseFile() {
      if (this.uploading) return
      
      uni.chooseFile({
        count: 1,
        type: 'file',
        extension: ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'],
        success: (res) => {
          const file = res.tempFiles[0]
          
          // 检查文件大小 (50MB)
          if (file.size > 50 * 1024 * 1024) {
            uni.showToast({
              title: '文件大小不能超过50MB',
              icon: 'none'
            })
            return
          }
          
          this.selectedFile = {
            path: file.path,
            name: file.name,
            size: file.size,
            type: file.type || this.getFileTypeFromName(file.name)
          }
        },
        fail: (err) => {
          console.error('选择文件失败:', err)
          if (err.errMsg !== 'chooseFile:fail cancel') {
            uni.showToast({
              title: '选择文件失败',
              icon: 'none'
            })
          }
        }
      })
    },
    
    // 移除选中的文件
    removeFile() {
      this.selectedFile = null
      this.uploadProgress = 0
    },
    
    // 上传文件
    async uploadFile() {
      if (!this.selectedFile || this.uploading) return
      
      this.uploading = true
      this.uploadProgress = 0
      
      try {
        const uploadTask = uni.uploadFile({
          url: this.$config.baseURL + '/api/files/upload',
          filePath: this.selectedFile.path,
          name: 'file',
          header: {
            'Authorization': 'Bearer ' + this.$store.state.user.token
          },
          success: (res) => {
            if (res.statusCode === 200) {
              const data = JSON.parse(res.data)
              if (data.success) {
                uni.showToast({
                  title: '上传成功',
                  icon: 'success'
                })
                
                // 重置状态
                this.selectedFile = null
                this.uploadProgress = 0
                
                // 刷新最近文件列表
                this.loadRecentFiles()
                
                // 触发上传成功事件
                this.$emit('uploadSuccess', data.data)
                
                // 延迟跳转到文件详情页
                setTimeout(() => {
                  uni.navigateTo({
                    url: `/pages/files/detail?id=${data.data.id}`
                  })
                }, 1500)
              } else {
                throw new Error(data.message || '上传失败')
              }
            } else {
              throw new Error('上传失败')
            }
          },
          fail: (err) => {
            console.error('上传失败:', err)
            throw new Error('网络错误，上传失败')
          }
        })
        
        // 监听上传进度
        uploadTask.onProgressUpdate((res) => {
          this.uploadProgress = res.progress
        })
        
      } catch (error) {
        console.error('上传文件失败:', error)
        uni.showToast({
          title: error.message || '上传失败',
          icon: 'none'
        })
      } finally {
        this.uploading = false
      }
    },
    
    // 加载最近上传的文件
    async loadRecentFiles() {
      try {
        const response = await this.$http.get('/api/files', {
          params: { page: 1, limit: 5 }
        })
        
        if (response.data.success) {
          this.recentFiles = response.data.data.files || []
        } else {
          this.recentFiles = []
        }
      } catch (error) {
        console.error('加载最近文件失败:', error)
        this.recentFiles = []
      }
    },
    
    // 查看文件
    viewFile(file) {
      uni.navigateTo({
        url: `/pages/files/detail?id=${file.id}`
      })
    },
    
    // 查看所有文件
    viewAllFiles() {
      uni.navigateTo({
        url: '/pages/files/list'
      })
    },
    
    // 获取文件图标
    getFileIcon(fileType) {
      if (!fileType) return 'file-text'
      
      if (fileType.includes('pdf')) return 'file-pdf'
      if (fileType.includes('word') || fileType.includes('document')) return 'file-word'
      if (fileType.includes('excel') || fileType.includes('sheet')) return 'file-excel'
      if (fileType.includes('powerpoint') || fileType.includes('presentation')) return 'file-ppt'
      if (fileType.includes('image')) return 'image'
      if (fileType.includes('text')) return 'file-text'
      
      return 'file'
    },
    
    // 从文件名获取类型
    getFileTypeFromName(fileName) {
      const ext = fileName.split('.').pop().toLowerCase()
      const typeMap = {
        'pdf': 'application/pdf',
        'doc': 'application/msword',
        'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'xls': 'application/vnd.ms-excel',
        'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'ppt': 'application/vnd.ms-powerpoint',
        'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
        'txt': 'text/plain',
        'jpg': 'image/jpeg',
        'jpeg': 'image/jpeg',
        'png': 'image/png',
        'gif': 'image/gif',
        'bmp': 'image/bmp',
        'webp': 'image/webp'
      }
      return typeMap[ext] || 'application/octet-stream'
    },
    
    // 格式化文件大小
    formatFileSize(bytes) {
      if (!bytes || bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    },
    
    // 格式化时间
    formatTime(dateString) {
      if (!dateString) return '未知时间'
      
      const date = new Date(dateString)
      const now = new Date()
      const diff = now - date
      
      if (diff < 60000) return '刚刚'
      if (diff < 3600000) return Math.floor(diff / 60000) + '分钟前'
      if (diff < 86400000) return Math.floor(diff / 3600000) + '小时前'
      if (diff < 604800000) return Math.floor(diff / 86400000) + '天前'
      
      return date.toLocaleDateString()
    }
  }
}
</script>

<style lang="scss" scoped>
.file-upload-page {
  min-height: 100vh;
  background-color: #f8f9fa;
  padding-bottom: 40rpx;
}

.upload-section {
  background: white;
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.upload-tips {
  display: flex;
  align-items: flex-start;
  margin-bottom: 30rpx;
  padding: 20rpx;
  background-color: #f0f5ff;
  border-radius: 12rpx;
  
  .tips-text {
    margin-left: 12rpx;
    font-size: 28rpx;
    color: #606266;
    line-height: 1.5;
  }
}

.upload-area {
  border: 2rpx dashed #dcdfe6;
  border-radius: 12rpx;
  padding: 60rpx 40rpx;
  text-align: center;
  margin-bottom: 30rpx;
  transition: all 0.3s ease;
  
  &:active {
    border-color: #4a6bef;
    background-color: #f0f5ff;
  }
}

.upload-placeholder {
  .placeholder-text {
    display: block;
    margin-top: 20rpx;
    font-size: 32rpx;
    color: #606266;
    font-weight: 500;
  }
  
  .placeholder-desc {
    display: block;
    margin-top: 12rpx;
    font-size: 26rpx;
    color: #909399;
  }
}

.selected-file {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx;
  background-color: #f0f5ff;
  border-radius: 12rpx;
  
  .file-info {
    display: flex;
    align-items: center;
    flex: 1;
    overflow: hidden;
    
    .file-icon {
      width: 80rpx;
      height: 80rpx;
      background: #e0e9ff;
      border-radius: 12rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 20rpx;
    }
    
    .file-details {
      flex: 1;
      overflow: hidden;
      
      .file-name {
        display: block;
        font-size: 30rpx;
        color: #303133;
        font-weight: 500;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      
      .file-size {
        display: block;
        font-size: 26rpx;
        color: #909399;
        margin-top: 8rpx;
      }
    }
  }
  
  .file-remove {
    margin-left: 20rpx;
    padding: 10rpx;
    
    &:active {
      opacity: 0.7;
    }
  }
}

.upload-progress {
  margin-bottom: 30rpx;
  
  .progress-text {
    display: block;
    text-align: center;
    font-size: 28rpx;
    color: #4a6bef;
    margin-top: 16rpx;
  }
}

.upload-btn {
  width: 100%;
  height: 88rpx;
  border-radius: 44rpx;
  background: #4a6bef;
  color: white;
  font-size: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  transition: all 0.3s ease;
  
  &:active {
    opacity: 0.9;
    transform: scale(0.98);
  }
  
  &.disabled {
    background: #c0c4cc;
    opacity: 0.7;
  }
  
  .loading-icon {
    margin-right: 10rpx;
    animation: rotate 1s linear infinite;
  }
  
  @keyframes rotate {
    from { transform: rotate(0deg); }
    to { transform: rotate(360deg); }
  }
}

.recent-files, .supported-types {
  background: white;
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.section-title {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
  
  .title-bar {
    width: 6rpx;
    height: 32rpx;
    background: #4a6bef;
    border-radius: 3rpx;
    margin-right: 16rpx;
  }
  
  text {
    font-size: 32rpx;
    font-weight: 600;
    color: #303133;
    flex: 1;
  }
  
  .view-all {
    font-size: 28rpx;
    color: #4a6bef;
    font-weight: normal;
  }
}

.file-list {
  .file-item {
    display: flex;
    align-items: center;
    padding: 24rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    &:active {
      background: #f9f9f9;
    }
    
    .file-icon {
      width: 60rpx;
      height: 60rpx;
      background: #f0f5ff;
      border-radius: 12rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 20rpx;
    }
    
    .file-info {
      flex: 1;
      overflow: hidden;
      
      .file-name {
        display: block;
        font-size: 30rpx;
        color: #303133;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        margin-bottom: 8rpx;
      }
      
      .file-meta {
        font-size: 26rpx;
        color: #909399;
      }
    }
  }
}

.type-list {
  .type-category {
    margin-bottom: 30rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .category-header {
      display: flex;
      align-items: center;
      margin-bottom: 16rpx;
      
      .category-title {
        font-size: 30rpx;
        color: #303133;
        font-weight: 500;
        margin-left: 12rpx;
      }
    }
    
    .type-items {
      display: flex;
      flex-wrap: wrap;
      gap: 16rpx;
      
      .type-tag {
        padding: 8rpx 20rpx;
        background: #f0f5ff;
        color: #4a6bef;
        font-size: 26rpx;
        border-radius: 30rpx;
      }
    }
  }
}

.upload-notes {
  margin-top: 30rpx;
  padding-top: 30rpx;
  border-top: 1rpx solid #f0f0f0;
  
  .note-item {
    display: flex;
    align-items: center;
    margin-bottom: 16rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    text {
      margin-left: 12rpx;
      font-size: 28rpx;
      color: #606266;
    }
  }
}
</style>